import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=144 lang=java
 *
 * [144] 二叉树的前序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {

    /**
     * 迭代法
     * 
     * Accepted
    69/69 cases passed (0 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 90.84 % of java submissions (39.4 MB)
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> deque = new LinkedList<>();
        while (root != null || !deque.isEmpty()) {
            while (root != null) {
                res.add(root.val);
                deque.push(root);
                root = root.left;
            }
            root = deque.pop().right;
        }
        return res;
    }

    /**
     * 递归法
     */
    public void traversal(TreeNode root, List<Integer> res) {
        if (root == null)
            return;
        res.add(root.val);
        traversal(root.left, res);
        traversal(root.right, res);
    }
}
// @lc code=end
